package service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.preference.PreferenceActivity;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import com.example.pos_terminal.MainActivity;
import com.example.pos_terminal.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import bean.AraStoreLog;
import bean.ResultEntity;
import bean.TradeAccountConsumptionFlow;
import bean.TradeConsumptionDetail;
import bean.TradeConsumptionMain;
import config.CommonValue;
import config.QYRestClient;
import db.TaskManager;
import push.DetectTools;
import receiver.AlarmSyncReceiver;
import tools.AppException;
import tools.GsonTools;
import tools.Logger;
import tools.TimeTools;

import static com.example.pos_terminal.MainActivity.timeStop;
import static tools.GetMacAddress.getMacAddress;

//import bean.SpecimenUpload;

/**
 * Created by TJ on 2016/3/22.
 */
public class TimerSyncService extends Service {

    private static final String TAG = "TimerSyncService";


    private  List<AraStoreLog> uploadAraStoreLog;
    private  List<TradeAccountConsumptionFlow> uploadConsumptionFlow;
    private  List<TradeConsumptionMain> uploadConsumptionMain = new ArrayList<>();
    private  List<TradeConsumptionDetail> uploadConsumptionDetail= new ArrayList<>();
    private TaskManager manager;
    private WifiManager wifi;
    static final String NOTIFICATION_ID = "1111";
    static final String NOTIFICATION_NAME = "aaa";
    @Override
    public IBinder onBind(Intent intent) {
        if (CommonValue.isDebug) Log.i("TimerSyncService", "onBind start...");
        return null;
    }

    private static final long DELETE_OLD_DATA_INTERVAL = 60000;
    private long tenTime = TimeTools.timingTen(8);//上次检查时间(毫秒数)
    private long oldTenTime = 0;
    private long sevenTime = TimeTools.timingTen(19);//上次检查时间(毫秒数)
    private long lastSyncTime = 0;//上次同步时间(毫秒数)
    private long lastDeleteTime = 0;//上次删除数据时间(毫秒数)
//    private final long spacingTimes = 1000*60;//同步时间
    private final long spacingTimes = 1000*60*60*3;//同步时间

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NotificationManager notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        //创建NotificationChannel
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_ID, NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        //Android9.0会报Caused by: java.lang.SecurityException: Permission Denial:
        //android.permission.FOREGROUND_SERVICE---AndroidManifest.xml中需要申请此权限
        startForeground(1,getNotification());
        acquireWakeLock();
        if (CommonValue.isDebug) Log.i("TimerSyncService", "onStartCommand:" + new java.util.Date().toLocaleString());
        timeStop=false;
        final long currentMillis = System.currentTimeMillis();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    acquireWakeLock();
                    manager = TaskManager.getInstance(getApplicationContext());
                    if(currentMillis - lastDeleteTime >= DELETE_OLD_DATA_INTERVAL){
                        lastDeleteTime = currentMillis;
                        manager.deleteOldData();
                    }
                        try {// 2.处理定时上传(同步)任务功能
                            Calendar instance = Calendar.getInstance();
                            for ( int i = 0; i < 5; i++) {
                                String startTime = TimeTools.startOfDay((Calendar) instance.clone());
                                String endTime = TimeTools.endOfDay((Calendar) instance.clone());
                                uploadConsumptionFlow = manager.queryUploadConsumptionFlow(startTime, endTime, null);
                                if (uploadConsumptionFlow.size()>0){
                                    processUploadFlow();
                                }
                                uploadAraStoreLog = manager.queryUploadAraStoreLog(startTime, endTime);
                                if (uploadAraStoreLog.size()>0){
                                    processUploadAraLog();
                                }
                                instance.add(Calendar.DAY_OF_YEAR, -1);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }finally {
                            timeStop = true;
                        }
                    DetectTools.setTimeout(TimerSyncService.this, AlarmSyncReceiver.class, spacingTimes);
                    System.out.println("定时上传订单任务结束"+TimeTools.calendar2String(Calendar.getInstance()));
                    System.out.println("定时上传订单任务下次执行时间"+TimeTools.calendar2String(Calendar.getInstance()));
                    tryReleaseWakeLock(false);
                }
            }).start();
        tryReleaseWakeLock(false);
        return super.onStartCommand(intent, START_FLAG_RETRY, startId);
    }


    /**
     * 处理flow三个表数据上传
     *
     */
    private void processUploadFlow() {
        final long currentMillis = System.currentTimeMillis();//超过指定间隔时间后才执行
        if (CommonValue.isDebug) Log.i("TimerSyncService", "Task sync(upload) executed: " + new java.util.Date(currentMillis).toLocaleString());


        for (TradeAccountConsumptionFlow flow:uploadConsumptionFlow) {

            List<TradeConsumptionMain>  mains = manager.listTradeTask(flow.getFlowNo());
            flow.setMainLists(mains);

        }


        Log.e("Flow上传",uploadConsumptionFlow!=null?uploadConsumptionFlow.size()+"":"null");

        RequestParams params = new RequestParams();
        params.add("uploadConsumptionFlow", GsonTools.toJson(uploadConsumptionFlow));


        String SerialNumber = android.os.Build.SERIAL;
        params.add("macAddress",getMacAddress());
        Log.e("SerialNumber",SerialNumber);
        QYRestClient.post("uploadFlowTask.do", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String res = new String(responseBody).trim();

                ResultEntity resultEntity = null;
                try {
                    resultEntity = GsonTools.parse(res, ResultEntity.class);
                } catch (AppException e) {
                    e.printStackTrace();
                }

                if (resultEntity != null && CommonValue.OPT_OK == resultEntity.getResult()){
                    String data = resultEntity.getData();
                    List<String> okFlowLists = new Gson().fromJson(data, new TypeToken<List<String>>(){}.getType());
                    manager.updateStatusFlow(uploadConsumptionFlow, okFlowLists);
                }
                lastSyncTime = currentMillis;//操作成功后更新上次同步时间
//                try {
//                    Log.i("上传返回的信息--------",res);
//                    if (res.contains("SUCCESS")){//传输成功执行更新，否则不做操作
//                        updateStatusFlow();
//                        lastSyncTime = currentMillis;//操作成功后更新上次同步时间
//                    }
//                } catch (Exception e) {
//                    if (CommonValue.isDebug) Logger.e(e);
//                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable throwable) {
            }
        });
    }

    //更新flow三个表数据上传
    private void updateStatusFlow() {
        //更新状态
        for (TradeAccountConsumptionFlow entity:uploadConsumptionFlow) {
            ContentValues values = new ContentValues();
            values.put("isXmlOut","1");//key为字段名，value为值
            manager.update("trade_account_consumption_flow",values,"id=?",new String[]{entity.getId()} );
        }
        for (TradeConsumptionMain entity:uploadConsumptionMain) {
            ContentValues values = new ContentValues();
            values.put("isXmlOut","1");//key为字段名，value为值
            manager.update("trade_consumption_main",values,"id=?",new String[]{entity.getId()} );
        }
        for (TradeConsumptionDetail entity:uploadConsumptionDetail) {
            ContentValues values = new ContentValues();
            values.put("isXmlOut","1");//key为字段名，value为值
            manager.update("trade_consumption_detail",values,"id=?",new String[]{entity.getId()} );
        }


    }

 /**
     * 处理微信log表数据上传
     *
     */
    private void processUploadAraLog() {
        final long currentMillis = System.currentTimeMillis();//超过指定间隔时间后才执行
        if (CommonValue.isDebug) Log.i("TimerSyncService", "Task sync(upload) executed: " + new java.util.Date(currentMillis).toLocaleString());

//         uploadAraStoreLog = manager.queryUploadAraStoreLog();

        Log.e("log上传",uploadAraStoreLog.size()+"");

        RequestParams params = new RequestParams();
        params.add("uploadAraStoreLog", GsonTools.toJson(uploadAraStoreLog));

       /* WifiInfo info = wifi.getConnectionInfo();
        String macAddress = info.getMacAddress();
        params.add("macAddress",macAddress);*/
        QYRestClient.post("uploadAraStoreLog.do", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String res = new String(responseBody).trim();
                try {
                    Log.i("上传返回的信息--------",res);
                    if (res.contains("SUCCESS")){//传输成功执行更新，否则不做操作
                        updateStatusAraLog();
                        lastSyncTime = currentMillis;//操作成功后更新上次同步时间
                    }
                } catch (Exception e) {
                    if (CommonValue.isDebug) Logger.e(e);
                }
            }

            @Override
            public void onFailure(int i, org.apache.http.Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }
    //更新log表数据上传
    private void updateStatusAraLog() {
        //更新状态
        for (AraStoreLog entity:uploadAraStoreLog) {
            ContentValues values = new ContentValues();
            values.put("isSyn","1");//key为字段名，value为值
            manager.update("ara_store_log",values,"id=?",new String[]{entity.getId()} );
        }
    }

    private PowerManager.WakeLock wakeLock;
    private int lockCount = 0;
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();
        if (CommonValue.isDebug) Log.i("TimerSyncService", "onCreate start...");
        final Context appContext = getApplicationContext();
        wifi = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
        newWakeLock(appContext);

//        startMyOwnForeground();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationBuilder builder = new NotificationBuilder(this);
            final Notification notification = builder.buildNotification();
            startForeground(NotificationBuilder.NOTIFICATION_ID, notification);
            startService(new Intent(TimerSyncService.this, InnerService.class));
        } else {
            startService(new Intent(TimerSyncService.this, InnerService.class));
        }
    }

    @Override
    public void onDestroy() {
        if (CommonValue.isDebug) Log.i("TimerSyncService", "onDestroy start...");
        //DetectTools.clearTimeout(this, AlarmSyncReceiver.class);
        tryReleaseWakeLock(true);
        super.onDestroy();
    }

    protected void newWakeLock(Context appContext) {
        PowerManager powerManager = (PowerManager)appContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ON_AFTER_RELEASE, getClass().getSimpleName());
        if (wakeLock != null) { wakeLock.setReferenceCounted(false); }
    }
    protected synchronized void acquireWakeLock() {
        if (wakeLock != null) {
            if (!wakeLock.isHeld()) {
                wakeLock.acquire();
            }
            lockCount++;
        }
    }
    protected synchronized void tryReleaseWakeLock(boolean destroy) {
        if (wakeLock != null) {
            if (lockCount > 0) { lockCount--; }
            if (destroy || lockCount == 0) {
                if (wakeLock.isHeld()) {
                    wakeLock.release();
                }
            }
        }
    }
//
//    private static Notification newNotification(Context context) {
//        Notification notification = null;
//        if(Build.VERSION.SDK_INT >= 16) {
//            notification = new Notification.Builder(context).build();
//        } else { notification = new Notification(); }
//        notification.flags = Notification.FLAG_ONGOING_EVENT;
//        notification.flags |= Notification.FLAG_NO_CLEAR;
//        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
//        return notification;
//    }

    //这个必须加，不能设置为null
    private Notification getNotification() {
        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("数据定时上传")
                .setContentText("运行中");//标题和内容可以不加
        //设置Notification的ChannelID,否则不能正常显示
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(NOTIFICATION_ID);
        }
        Notification notification = builder.build();
        return notification;
    }


    public static class InnerService extends Service {
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        @Override
        public void onCreate() {
            super.onCreate();
            //startForeground(NOTIFICATION_ID, newNotification(this));
            stopSelf();
        }
        @Override
        public void onDestroy() {
            stopForeground(true);
            super.onDestroy();
        }
    }
}
